package com.qf.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.pojo.TbBrand;
import com.qf.pojo.TbCategory;
import com.qf.pojo.TbGood;
import com.qf.service.BrandService;
import com.qf.service.CategoryService;
import com.qf.service.GoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private GoodService goodService;

    @RequestMapping("index")
    public String index(Model model,
                        String categoryId,
                        String brandId,
                        @RequestParam(defaultValue = "1") Integer pageNum,
                        @RequestParam(defaultValue = "2") Integer pageSize){
        List<TbCategory> categoryList = categoryService.selectAll();
        //1.如果没有传递分类id,那么默认使用第一个分类的id
        if(categoryId == null){
            categoryId = String.valueOf(categoryList.get(0).getCategoryId());
        }
        //将分类id保存到域对象中去
        model.addAttribute("categoryId",categoryId);
        model.addAttribute("categoryList",categoryList);

        //2.根据分类id查询所有品牌
        List<TbBrand> brandList = brandService.selectBrandByCategoryId(categoryId);
        model.addAttribute("brandList",brandList);

        //3.根据品牌id和分类id查询商品
        if(brandList != null && brandList.size() > 0){
            if (brandId == null){
                brandId = String.valueOf(brandList.get(0).getBrandId());
            }
            model.addAttribute("brandId",brandId);
            Page<TbGood> page = goodService.selectGoodByIdAndCategoryById(brandId, categoryId,pageNum,pageSize);
            model.addAttribute("goodList",page.getRecords());//分页数据
            model.addAttribute("current",page.getCurrent());//当前页
            model.addAttribute("total",page.getTotal());//总条数
            model.addAttribute("pages",page.getPages());//总页数
            model.addAttribute("size",page.getSize());//每一页条数
        }

        return "index";
    }
}
